package com.my.app.monitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.my.annotation.Return;
import com.my.framework.web.annotation.Query;
import com.my.framework.web.filters.QueueFilter.QueueInfo;
import com.my.framework.web.mvc.controller.BaseController;
import com.my.monitor.Monitor;
import com.my.monitor.MonitorFacade;
import com.my.monitor.TimeMonitor;
import com.my.monitor.TimeStatist;

@Controller
@RequestMapping("/app/monitor")
public class MonitorController extends BaseController{

	
	@Query(name="获得所有耗时的监控项",path="/time")
	@Return("时间统计监控项列表")
	public List<Map<String,String>> time(String host,Integer port){
		List list=new ArrayList();
		TimeMonitor tm=(TimeMonitor) MonitorFacade.getMonitor(MonitorFacade.HTTP_MONITOR);
		tm.getMap().forEach((name,st)->{
			Map map=new LinkedHashMap();
			for(int i=0;i<st.getAccuracyCount().length;i++) {
				if(i==st.getAccuracy().length) {
					map.put("{#ITEM"+i+"}",">"+st.getAccuracy()[i-1]);
				}else {
					long begin=0;
					if(i!=0) {
						begin=st.getAccuracy()[i-1];
					}
					map.put("{#ITEM"+i+"}",begin+"-"+st.getAccuracy()[i]);
				}
				
			}
			map.put("{#NAME}",name);
			map.put("{#URL}", "/app/monitor/timeValue");
			list.add(map);
		});
		return list;
	}
	
	@Query(name="获取单个统计项的值",path="timeValue")
	public String timeValue(String name,String type){
		try {
			TimeMonitor tm=(TimeMonitor) MonitorFacade.getMonitor(MonitorFacade.HTTP_MONITOR);
			TimeStatist st=tm.get(name);
			if(st==null) {
				//log.info("找不到监控项:"+name);
				return "0";
			}
			int num=Integer.parseInt(type);
			return st.getAccuracyCount()[num].get()+"";
		}catch(Exception ex) {
			ex.printStackTrace();
			log.error("请求参数不正确:"+name+":"+type+","+ex.getMessage());
			return "";
		}
	}
	
	@Query(name="获取所有队列监控项",path="/queue")
	public List<Map<String,String>> queue(String host,Integer port) {
		Monitor mo=MonitorFacade.getMonitor(MonitorFacade.QUEUE_MONITOR);
		if(mo==null) {
			return new ArrayList();
		}
		Map map=mo.getReslut();
		List list=new ArrayList();
		map.forEach((key,value)->{
			Map item=new HashMap();
			item.put("{#ITEM0}", "remain");
			item.put("{#ITEM1}", "size");
			item.put("{#NAME}", key);
			item.put("{#URL}", "/app/monitor/queueValue");
			list.add(item);
		});
		return list;
	}
	
	@Query(name="获取单个队列值",path="queueValue")
	public String queueValue(String name,String type) {
		Monitor mo=MonitorFacade.getMonitor(MonitorFacade.QUEUE_MONITOR);
		Map<String,Object> map=mo.getReslut();
		QueueInfo info=(QueueInfo)map.get(name);
		if(info==null) {
			return "";
		}
		if("size".contentEquals(type)) {
			return info.getSize()+"";
		}else {
			return info.getRemain()+"";
		}
	}
}
